
package com.limoilux.cobolux.core;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;


public class SourceCreator extends RessourceCreator
{
	private static final String DEF_TAB = "       ";

	public String fileName = null;
	public String containerName = null;

	private InputStream openContentStream()
	{
		String contents = "";

		contents += DEF_TAB + "IDENTIFICATION DIVISION.\n";
		contents += DEF_TAB + "PROGRAM-ID.    unNom.\n";
		contents += DEF_TAB + "PROCEDURE DIVISION.\n";
		contents += DEF_TAB + "00000-PRINCIPAL.\n";
		contents += DEF_TAB + "    " + "STOP RUN.\n";

		return new ByteArrayInputStream(contents.getBytes());
	}

	@Override
	public void create(IProgressMonitor monitor, IWorkspaceRoot root) throws CoreException
	{
		IContainer container = null;
		IResource resource = null;
		InputStream stream = null;

		// create a sample file
		monitor.beginTask("Creating " + fileName, 2);
		root = ResourcesPlugin.getWorkspace().getRoot();
		resource = root.findMember(new Path(containerName));

		if (!resource.exists() || !(resource instanceof IContainer))
		{
			throwCoreException("Container \"" + containerName + "\" does not exist.");
		}

		container = (IContainer) resource;
		final IFile file = container.getFile(new Path(fileName));

		try
		{
			stream = this.openContentStream();
			if (file.exists())
			{
				file.setContents(stream, true, true, monitor);
			}
			else
			{
				file.create(stream, true, monitor);
			}
			stream.close();
		}
		catch (IOException e)
		{
		}

		monitor.worked(1);
	}

	private void throwCoreException(String message) throws CoreException
	{
		IStatus status = new Status(IStatus.ERROR, "com.limoilux.cobolux.manager", IStatus.OK, message, null);
		throw new CoreException(status);
	}

}
